package tech.yixiyun.framework.kuafu.component.register;


import tech.yixiyun.framework.kuafu.bean.BeanContext;
import tech.yixiyun.framework.kuafu.bean.BeanDefinition;
import tech.yixiyun.framework.kuafu.bean.annotation.Bean;
import tech.yixiyun.framework.kuafu.bean.annotation.ClassInitialize;
import tech.yixiyun.framework.kuafu.component.Component;
import tech.yixiyun.framework.kuafu.component.ComponentResolveException;
import tech.yixiyun.framework.kuafu.context.ApplicationContext;

import java.lang.annotation.Annotation;

/**
 * 最基础的组件注册器，属于框架内置的组件类，都会在这注册
 * @author Yixiyun
 * @date 2021-04-09 11:10
 * @version 1.0
 */
public class BeanComponentRegistrar implements IComponentRegistrar {
    @Override
    public void register(Class clazz) {
        //如果类上有ClassInitialize注解，要进行类的初始化，其他的不用，以便加快启动速度
        if (clazz.isAnnotationPresent(ClassInitialize.class)) {
            try {
                clazz = Class.forName(clazz.getName(), true, ApplicationContext.getServletContext().getClassLoader());
            } catch (ClassNotFoundException e) {
                throw new ComponentResolveException(e);
            }
        }
        Bean bean = (Bean) clazz.getAnnotation(Bean.class);
        if (bean != null) {
            BeanDefinition definition = new BeanDefinition(clazz);
            BeanContext.register(clazz, definition);
        } else if (isComponent(clazz)){
            BeanContext.register(clazz, new BeanDefinition(clazz));
        }
    }


    /**
     * 判断是不是组件类
     * @param clazz
     * @return
     */
    private static boolean isComponent(Class clazz) {
        Annotation[] annotations = clazz.getAnnotations();
        if (annotations != null) {
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().isAnnotationPresent(Component.class)) {
                    return true;
                }
            }
        }

        while (clazz != null && clazz != Object.class) {
            Class[] interfaces = clazz.getInterfaces();
            if (interfaces != null && interfaces.length > 0) {
                for (Class in : interfaces) {
                    if (in.isAnnotationPresent(Component.class)) {
                        return true;
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }

        return false;



    }


}
